package com.hmy.infrastructure.service.corpsearch.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.json.JSONUtil;
import com.hmy.infrastructure.common.constant.QichachaConstants;
import com.hmy.infrastructure.common.properties.QichachaProperties;
import com.hmy.infrastructure.common.utils.QichachaHttpUtil;
import com.hmy.infrastructure.service.dto.qichacha.QichachaBaseDto;
import com.hmy.infrastructure.service.dto.qichacha.QichachaCorpBasicDetailDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.HttpHead;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 调用企查查的接口，接口中的参数必须和接口文档中保持一致，不能多参数
 * @Author seven.qi
 * @Date 2023/11/27 10:49
 * @Version 1.0
 */

@Service
@Slf4j
public class QichachaCorpSearchBaseService {

    @Resource
    protected QichachaProperties qichachaProperties;

    private static final String app_key = "key";

    //==========业务功能实现======================

    protected String nameSearch(String uri, Map<String, Object> paramsMap) throws Exception {
        Map<String, Object> requestParamsMap = new HashMap<>();
        requestParamsMap.put("searchName", paramsMap.get("searchName"));
        requestParamsMap.put(app_key, qichachaProperties.getAppKey());
        return doGet(uri, requestParamsMap);
    }

    /**
     * 调用企查查【410】企业工商照面接口
     * 实时查询企业工商照面信息，返回企业名称、企业类型、注册资本、统一社会信用代码、经营范围、营业期限、上市状态等信息。
     *
     * @param params 请求参数
     * @return 查询结果
     * @throws Exception
     * @author songkf
     */
    protected QichachaCorpBasicDetailDto basicDetailsByName(Map<String, Object> params) throws Exception {
        params.put("searchKey", params.get("corpName"));
        QichachaBaseDto<QichachaCorpBasicDetailDto> result = get(QichachaConstants.URI_BASIC_DETAILS_BY_NAME, params);
        log.info("调用企查查的【410】企业工商照面接口,请求ID是:{},请求地址是:{},请求参数是:{},响应结果是:{}", result.getOrderNumber(), QichachaConstants.URI_BASIC_DETAILS_BY_NAME, JSONUtil.toJsonStr(params), JSONUtil.toJsonStr(result));
        if (result.isSuccess()) {
            throw new RuntimeException(String.format("调用企查查的【410】企业工商照面接口失败,调用请求序列号是:%s,异常提示信息是:%s", result.getOrderNumber(), result.getMessage()));
        }
        return result.getResult();
    }

    //==================基础功能实现==================

    protected String doGet(String uri, Map<String, Object> paramsMap) throws Exception {
        if (qichachaProperties.getTestingMode()) {
            return testingMode(uri);
        }
        if (!paramsMap.containsKey(app_key)) {
            paramsMap.put(app_key, qichachaProperties.getAppKey());
        }
        HttpHead httpHead = new HttpHead();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        httpHead.setHeader("Token", getToken(timestamp));
        httpHead.setHeader("Timespan", timestamp);
        String requestUrl = qichachaProperties.getServerUrl().concat(uri).concat(convertMapToHeaderString(paramsMap));
        log.info("request qichacha url : {}", requestUrl);
        String result = QichachaHttpUtil.httpGet(requestUrl, httpHead.getAllHeaders());
        log.info("qichacha result : {}", result);
        return result;
    }

    private <T> QichachaBaseDto<T> get(String uri, Map<String, Object> params) throws Exception {
        return JSONUtil.toBean(doGet(uri, params), QichachaBaseDto.class);
    }


    private String getToken(String timestamp) {
        return DigestUtils.md5Hex(qichachaProperties.getAppKey().concat(timestamp).concat(qichachaProperties.getSecretKey())).toUpperCase();
    }

    public static String convertMapToHeaderString(Map<String, Object> params) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("?");
        for (String key : params.keySet()) {
            stringBuilder.append(key);
            stringBuilder.append("=");
            if (app_key.equals(key)) {
                stringBuilder.append(params.get(key));
            } else {
                stringBuilder.append(URLEncoder.createDefault().encode(params.get(key).toString(), Charset.defaultCharset()));
            }
            stringBuilder.append("&");
        }
        return stringBuilder.substring(0, stringBuilder.lastIndexOf("&"));
    }

    private String testingMode(String uri) {
        String fileName = "";
        if (uri.startsWith("/")) {
            fileName = uri.substring(1).replaceAll("/", ".");
        } else {
            fileName = uri.replaceAll("/", ".");
        }
        return FileUtil.readString(new File(getClass().getClassLoader().getResource("json").getPath(), fileName.concat(".json")).getAbsolutePath(), StandardCharsets.UTF_8);
    }
}
